import os
import requests

def transmit(address, post_data):
    # post_data的格式要按照企业微信机器人配置说明里的的要求来，这次用的是markdown格式
    # post_data = '{"msgtype" : "markdown", "markdown" : {"content": "%s"}}' % post_data
    post_data = '{"msgtype" : "text", "text" : {"content": "%s"}}' % post_data
    if address == '':
        print('URL地址为空！')
    else:
        r = requests.post(address, data=post_data.encode())
        rstr = r.json()
        if r.status_code == 200 and 'error' not in rstr:
            result = '发送成功'
            return result
        else:
            return 'Error'

def new_report(test_report):
    lists = os.listdir(test_report)
    # 列出目录的下所有文件和文件夹保存到lists
    lists.sort(key=lambda fn: os.path.getmtime(test_report + "/" + fn))  # 按时间排序
    file_new = os.path.join(test_report, lists[-1])
    # 获取最新的文件保存到file_ new
    script_path = os.path.realpath(file_new)
    return script_path

ftp_address = 'ftp://172.16.65.72:21/'
dist = 'F:\\FTP_test\\EGStar'
file_path = new_report(dist)
app_edition = file_path.rsplit('\\')[-1]

file = os.listdir(file_path)
file_path1 = file_path + '\\' + file[1]
download = dist.split('\\')
download_address = ftp_address + download[-1] + '/' + app_edition + '/'


sonnefile = open(file_path1, encoding='UTF-8')
content = sonnefile.readlines()
content2 = ''
for content1 in content[0:3]:
    content2 = content2 + content1

pwd = "ftptest/123456"

version1 = open(r"F:\PycharmProjects\workpython\getFTP\版本控制.txt", encoding='UTF-8')
version2 = version1.readlines()
version3 = version2[-1].replace('\n', '').replace('\r', '')

if __name__ == '__main__':
    # 机器人测试url
    # url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=a9801947-14cd-44bb-bb2c-2a3693c63ec0"
    # 正式推送url
    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bc5521ea-f4e1-4413-9d61-9495be0e909e"
    # 这个是你要调用的机器人地址，在群里添加了机器人之后就会有这个地址了，每个机器人只有一个地址

    # markdown格式发送
    # post_data1 = "> # 工程之星版本通知\n\n> ### 软件版本:" + app_edition + "\n\n> ### 更新内容:\n" + ">> " + content2 + ">> **详细内容请下载更新说明**\n\n>  账密：" + pwd + "\n\n>  软件下载/更新说明下载：" + download_address

    post_data1 = "工程之星版本通知\n软件版本:" + app_edition + "\n更新内容:\n" + content2 + "\n详细内容请下载更新说明\n账密：" + pwd + "\n软件下载/更新说明下载：" + download_address
    if version3 != app_edition:
        result = transmit(url, post_data1)
        version = open(r"F:\PycharmProjects\workpython\getFTP\版本控制.txt", "a+", encoding='UTF-8')
        version.write(app_edition)
        version.write('\n')
        version.close()
        print("写入成功")
